package com.whh.starter.web;

import com.whh.starter.config.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class SystemErrorController extends BasicErrorController {
    private static final Logger log = LoggerFactory.getLogger(SystemErrorController.class);

    public SystemErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @Override
    public Map<String, Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(request, options);
        refineErrorAttribute(errorAttributes);
        return errorAttributes;
    }

    /**
     * {
     * "timestamp": "2024-07-10T07:44:55.293+00:00",
     * "status": 404,
     * "error": "Not Found",
     * "message": "No message available",
     * "path": "/user"
     * }
     *
     * @param errorAttributes 默认
     */
    private void refineErrorAttribute(Map<String, Object> errorAttributes) {
        Object path = errorAttributes.get("path");
        Object exception = errorAttributes.get("error");
        Object message = errorAttributes.get("message");
        Object status = errorAttributes.get("status");
        StringBuilder sb = new StringBuilder();
        RequestContext currentContext = RequestContext.getCurrentContext();
        sb.append(path).append(", ").append(exception).append(", ").append(message);
        log.error("Error Controller: {}", sb);
        errorAttributes.clear();


        String newMessage = " Service Error: " + exception;

        if (message != null) {
            newMessage = " Service Error: " + message;
        }
        errorAttributes.put("code", status);
        errorAttributes.put("message", newMessage);
        errorAttributes.put("messageId", currentContext != null ? currentContext.getCorrelationId() : "");
    }
}
